package main

import (
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func Logger() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		file, _ := os.OpenFile("./1.txt", os.O_APPEND, 0777)
		defer file.Close()
		logger := logrus.New()
		logger.Formatter = &logrus.JSONFormatter{}
		logger.Out = file

		startTime := time.Now() // 记录请求开始时间

		// 在请求结束前，记录日志
		ctx.Next()

		// 记录请求结束时间和耗时
		endTime := time.Now()
		latency := endTime.Sub(startTime)
		logger.WithFields(logrus.Fields{
			"method":  ctx.Request.Method,
			"path":    ctx.Request.URL.Path,
			"ip":      ctx.ClientIP(),
			"latency": latency,
		}).Info("API request")
	}
}
